package com.ooho.filedownload;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Created by hugohoo on 10/15/16.
 */
public class FileDownload extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doGet(req, resp);

        String URI = req.getRequestURI();

        switch(URI){
            case "/filedownload/index":
                index(req, resp);
                break;
            case "/filedownload/download":
                download(req, resp);
            default:
                break;
        }

//        String filesPath = this.getServletContext().getRealPath("./WEB-INF/public/files");
//        File img = new File(filesPath + "/img.png");
//
//        try(FileInputStream ris = new FileInputStream(img)){
////            resp.addHeader("Content-Type", "image/png");
//            resp.addHeader("Content-Disposition", "attachment; filename=img.png");
//            IOUtils.copy(ris, resp.getOutputStream());
//        }
    }

    private void index(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String filesPath = this.getServletContext().getRealPath("./WEB-INF/public/files");
        File filesDir = new File(filesPath);

        String[] list = filesDir.list();

        req.setAttribute("files", list);
        getServletContext().getRequestDispatcher("/filedownload/index.jsp").forward(req, resp);
    }

    private void download(HttpServletRequest req, HttpServletResponse resp){
        String filesPath = this.getServletContext().getRealPath("./WEB-INF/public/files");
        String query = req.getQueryString();

        File file = new File(filesPath + "/" + query);

        try {
            try(FileInputStream ris = new FileInputStream(file)){
    //            resp.addHeader("Content-Type", "image/png");
                resp.addHeader("Content-Disposition", "attachment; filename=" + query);
                IOUtils.copy(ris, resp.getOutputStream());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
